//
//  LoginViewController.m
//  TodatPlay
//
//  Created by dllo on 16/9/16.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "ForgetViewController.h"
#import "FasterViewController.h"
#import "AFNetworking.h"
#import "LoginDataData.h"
#import "LoginData.h"
#import "LoginRootClass.h"
#import "LoginDataRootClass.h"
#import "LoginSuccessViewController.h"
#import "AppDelegate.h"
@interface LoginViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (nonatomic, strong) LoginRootClass *rootModel;
@property (nonatomic, strong) LoginDataRootClass *DataModel;

@end

@implementation LoginViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    // 使状态栏颜色为白色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
}


-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    // 是的状态栏颜色为黑色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"我的";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(handleRegister:)];
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icons_back_dark"] style:UIBarButtonItemStylePlain target:self action:@selector(handleLeft:)];
    

    self.phoneNumberTextField.delegate = self;
    
}
- (void)handleRegister:(UIBarButtonItem *)barButton {
    
    RegisterViewController *registerVC = [[RegisterViewController alloc] init];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:registerVC];
    [self presentViewController:navi animated:YES completion:nil];
    
}
- (void)handleLeft:(UIBarButtonItem *)btn {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - textfieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    if ([self valiMobile:textField.text]) {
        NSLog(@"这个是电话号");
    } else {
        NSLog(@"不是电话号");
        self.phoneNumberTextField.clearsOnBeginEditing = YES;
        self.phoneNumberTextField.placeholder = @"电话号不对";
    }
}
// 通过正则表达式判断电话输入框中的内容是否是电话号
- (BOOL)valiMobile:(NSString *)mobile
{
    
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

- (IBAction)handleLogin:(id)sender {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postURLString = @"http://wanapi.damai.cn/user/login.json";
    NSString *parameters = @"sign=20de956207dbbaadeff9f0470323ff54&source=10345&phone=15998571702&times=1472025153919&timestamp=1472025153&phonemodels=Letv+X501&platform=4&apptype=2&passwd=159263&systemversion=5.0.2&clientguid=8610540370029582&version=203004&ostype=2&channel_from=m360_market";
    
    NSArray *parameterArr = [NSArray array];
    NSMutableString *newParameters = [[NSMutableString alloc] init];
    // 将字符串通过"&"分割成一个个的字符串存放到数组中
    parameterArr = [parameters componentsSeparatedByString:@"&"];
    // 遍历数组
    for (NSString *parameter in parameterArr) {
        // 判断如果是第一个字符串则将其拼接到定义的可变字符串中
        if ([parameter containsString:@"sign"]) {
            [newParameters appendFormat:@"%@", parameter];
            // 判断如果数组中的字符串含有phone=, 则将其=后面的值换成电话号码输入框的值
        } else if ([parameter containsString:@"phone="]) {
            NSArray *phoneParameterArr = [parameter componentsSeparatedByString:@"="];
            NSString *phoneStr = phoneParameterArr[0];
            phoneStr = [phoneStr stringByAppendingFormat:@"=%@", self.phoneNumberTextField.text];
            // 拼接到可变字符串中
            [newParameters appendFormat:@"&%@", phoneStr];
            // 与上面同理
        } else if ([parameter containsString:@"passwd="]) {
            NSArray *passWordParameterArr = [parameter componentsSeparatedByString:@"="];
            NSString *passWordStr = passWordParameterArr[0];
            passWordStr = [passWordStr stringByAppendingFormat:@"=%@", self.passwordTextField.text];
            [newParameters appendFormat:@"&%@", passWordStr];
            // 通过"&"拼接剩下的字符串
        } else {
            [newParameters appendFormat:@"&%@", parameter];
        }
    }
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    // 3. 设置请求参数的字符串格式, 自定义
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return parameters;
    }];
    NSMutableSet *set = [NSMutableSet setWithSet:manager.responseSerializer.acceptableContentTypes];
    [set addObject:@"text/html"];
    [manager.responseSerializer setAcceptableContentTypes:set];
    
    [manager GET:postURLString parameters:newParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"登录请求成功: %@", responseObject);
        self.rootModel = [LoginRootClass modelWithDic:responseObject];
        /***************** 使用NSUeerDefaults存储信息 ******************/
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        [user setObject:responseObject forKey:@"LoginM"];
        [user synchronize];
        
        NSString *postURLString = @"http://wanapi.damai.cn/user/myview.json";
        NSMutableArray *arr = [NSMutableArray array];
        NSString *parameters = @"platform=4&channel_from=m360_market&source=10345&version=203004";
        // 将字符串通过&切割
        arr = [parameters componentsSeparatedByString:@"&"].mutableCopy;
        // 取出数组的第一个参数用来当第一个拼接的参数
        NSString *patameterss = arr[0];
        // 取出返回的参数值
        NSString *mCode = responseObject[@"data"][@"M"];
        // 将取出的参数拼接成"m=...."的格式
        NSString *strCode = [@"m" stringByAppendingFormat:@"=%@", mCode];
        // 拼接字符串
        
        patameterss = [patameterss stringByAppendingFormat:@"&%@&%@&%@&%@", arr[1], arr[2], strCode, arr[3]];
        NSLog(@"%@", patameterss);
        
        [manager GET:postURLString parameters:patameterss progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"返回都登录参数请求成功: %@", responseObject);
            self.DataModel = [LoginDataRootClass modelWithDic:responseObject];
            /***************** 使用NSUserDefault保存用户信息和账号密码 ******************/
            
            if (self.DataModel.errorCode == 0) {
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                [user setObject:responseObject forKey:@"LoginData"];
                [user setObject:self.phoneNumberTextField.text forKey:@"phoneNumber"];
                [user setObject:self.passwordTextField.text forKey:@"passWord"];
                [user synchronize];
                
                LoginSuccessViewController *successVC = [[LoginSuccessViewController alloc] init];
                successVC.data = self.DataModel.data;
                [self.navigationController pushViewController:successVC animated:YES];

            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"返回都登录参数请求失败: %@", error);
        }];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"登录请求失败: %@", error);
    }];

    
}
- (IBAction)forgotPassword:(id)sender {
    self.hidesBottomBarWhenPushed = YES;
     ForgetViewController *fogetVC = [[ForgetViewController alloc] init];
    [self.navigationController pushViewController:fogetVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;

}
- (IBAction)fasterLogin:(id)sender {
    
    self.hidesBottomBarWhenPushed = YES;
    FasterViewController *faster = [[FasterViewController  alloc] init];
    [self.navigationController pushViewController:faster animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
